package com.xixi.core.rpc.protocol;

import com.xixi.core.rpc.serializer.CustomSerializer;
import com.xixi.core.rpc.serializer.CustomSerializerFactory;
import io.vertx.core.buffer.Buffer;

import java.io.IOException;

/**
 * @author: zxh
 * @date: 2024/8/26 11:30
 * @description: 协议消息编码器
 */
public class ProtocolMessageEncoder {

	/**
	 * 编码
	 * @param message 待编码的内容
	 * @return 编码完成的字节流
	 * @throws IOException
	 */
	public static Buffer encode(ProtocolMessage<?> message) throws IOException {
		if (message == null || message.getHeader() == null) {
			return Buffer.buffer();
		}
		ProtocolMessage.Header header = message.getHeader();
		// 依次向缓冲区写入字节
		Buffer buffer = Buffer.buffer();
		buffer.appendByte(header.getMagic());
		buffer.appendByte(header.getVersion());
		buffer.appendByte(header.getSerializer());
		buffer.appendByte(header.getType());
		buffer.appendByte(header.getStatus());
		buffer.appendLong(header.getRequestId());
		// 获取序列化器
		ProtocolMessageSerializerEnum serializerEnum = ProtocolMessageSerializerEnum.getEnumByKey(header.getSerializer());
		if (serializerEnum == null) {
			throw new RuntimeException("序列化协议不存在");
		}
		CustomSerializer serializer = CustomSerializerFactory.getInstance(serializerEnum.getValue());
		byte[] bodyBytes = serializer.serialize(message.getBody());
		// 写入body长度和数据
		buffer.appendInt(bodyBytes.length);
		buffer.appendBytes(bodyBytes);
		return buffer;
	}
}
